#!/bin/env/ruby

# *Ruby-One-Click Installer for OSX lipo-hack*
# takes two arguments (directories) and does a recursive lipo,
# creating a new output-dir with the name 'output'

require 'find'
require 'fileutils'

include FileUtils::Verbose

if !ARGV[0] || !ARGV[1] then
  puts "Syntax: lipohack.rb dir1 dir2"
  puts "creates fat binaries/libraries of the two dirs"
  exit
end

new_dir = pwd + '/output/'
dir1 = File.expand_path( ARGV[0] ) + "/"
dir2 = File.expand_path( ARGV[1] ) + "/"

if File.directory?(new_dir) then 
  puts "output directory already exists!"
  puts "deleting the output dir ..."
  %x[/bin/rm -rf #{new_dir}]
end

chdir(dir2) do
  Find.find(dir1) do |path|
    fname = path.sub(dir1,'')
    fdir, base = File.split(fname)

    if File.directory?(path) then
      mkdir("#{new_dir}#{fname}")
    else
      r=%x[/usr/bin/file #{path}].split(':')[1]
     # if  r=~ /Mach-O executable/ || r =~ /Mach-O dynamically linked shared library/ || r =~ /Mach-O bundle/ then
     if r=~ /Mach-O/ then
       # we've got a file to lipo!
       %x[lipo -create #{dir1}#{fname} #{dir2}#{fname} -output #{new_dir}#{fname}]
       #puts "#{fname}"
      else
        # normal file, just copy
        %x[/bin/cp #{path} #{new_dir}#{fname}]
      end
    end
  end
end